<template>
  <el-dialog
    v-if="openForm"
    v-model="openBoole"
    :close-on-click-modal="false"
    custom-class="mydialog"
    width="50%"
    :title="title"
    @close="close"
  >
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="配送商名称" prop="distributeName">
            <el-autocomplete
              v-model="openForm.distributeName"
              style="width: 100%"
              placeholder="请选择配送商"
              :fetch-suggestions="querySearchAsync"
              placement="bottom"
              @select="handleSelect"
            >
              <template #default="{ item }">
                {{ item.distributeName }}
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="盘点时间" prop="checkTime">
            <date-picker v-model:date="openForm.checkTime" type="month" placeholder="选择月" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <item-title title="盘点产品明细">
            <template #btn>
              <el-button class="border-btn" size="mini" @click="handlAdd(null)">添加</el-button>
              <el-button class="border-btn" size="mini" @click="handlDele(null,1)">全部删除</el-button>
            </template>
          </item-title>
        </el-col>

        <el-col :span="24">
          <table-view
            :data="openForm.tableData"
            class="tableForm"
            header-cell-class-name="table-header"
            size="medium"
            border
          >

            <el-table-column type="index" label="序号" align="center" width="50" />

            <el-table-column label="产品通用名" align="center" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-form-item
                  label-width="0"
                  :prop="'tableData.' + scope.$index + '.productId'"
                  :rules="{ required: true, message: '请选择产品通用名', trigger: 'change'}"
                >
                  <el-select
                    v-model="scope.row.productId"
                    style="width: 100%"
                    placeholder="请选择产品通用名"
                    @change="()=>handlRddtype(scope.row.productId, scope.$index)"
                  >
                    <el-option
                      v-for="item in productList"
                      :key="item.id"
                      :label="`${item.productPopularName}-${item.packSpecs}`"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="商品名" prop="product.productName" align="center" :show-overflow-tooltip="true" />

            <el-table-column label="包装规格" prop="product.packSpecs" align="center" :show-overflow-tooltip="true" />

            <el-table-column label="库存数量" align="center" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-form-item
                  label-width="0"
                  :prop="'tableData.' + scope.$index + '.checkCount'"
                  :rules="{ required: true, message: '请选择产品通用名', trigger: 'blur'}"
                >
                  <el-input v-model.number="scope.row.checkCount" placeholder="请输入库存数量">
                    <template #append>
                      {{ getLabel('sell_unit',scope.row?.product?.sellUnit) }}
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="text" @click="handlAdd(scope)">编辑</el-button>
                <el-button type="text" @click="handlDelete(scope.$index,2)">删除</el-button>
              </template>
            </el-table-column>
          </table-view>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>

        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, toRefs,} from 'vue'

export default {
  name: 'RuleForm',
  setup(props, context) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const data = reactive({
      openBoole: false,
      openForm: {
        distributeName: '',
        distributeId: 0,
        checkTime: '',
        tableData: [],
      },
      rules: {
        distributeName: [
          { required: true, message: '请选择配送商', trigger: 'change' },
        ],
        checkTime: [
          { required: true, message: '请选择时间', trigger: 'change' },
        ],
      },
      openRef: null,
      productList: [],
    })

    const querySearchAsync = async(queryString, cb) => {
      let results = []
      const res = await api.terminal.PRODUCT_PULLLIST(queryString)
      if (res.code === 0) {
        results = res.data.list || []
      }
      cb(results)
    }

    const handleSelect = (val) => {
      if (val) {
        data.openForm.distributeName = val.distributeName
        data.openForm.distributeId = val.id
        handlProduct(val.id)
      }
    }

    const handlProduct = (id) => {
      api.inventory.INVENTORY_PRODUCT(id).then((res) => {
        if (res.code === 0) {
          data.productList = res.data || []
        }
      })
    }

    const handlRddtype = (id, index) => {
      const a = data.productList.filter((b) => b.id === id)
      const b = {
        product: a[0],
        productId: id,
        checkCount: '',
      }
      data.openForm.tableData[index] = b
    }

    const handlDate = (val) => {
      const date = new Date(val)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      return `${year}年${month}月`
    }

    const close = () => {
      data.openBoole = false
    }

    const open = () => {
      data.openBoole = true
    }

    const handlAdd = (val) => {
      if (val === null) {
        data.openForm.tableData.push({ productId: 0, checkCount: '' })
      } else {
        data.index = val.$index
      }
    }

    const handlDelete = (index, num) => {
      if (num === 1) {
        data.openForm.tableData.splice(index, 1)
      }
      if (num === 2) {
        data.openForm.tableData = []
      }
    }

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const arr = []
          data.openForm.tableData.forEach((item) => {
            arr.push({
              productId: item.productId,
              checkCount: item.checkCount,
            })
          })
          const obj = {
            distributeId: data.openForm.distributeId,
            checkTime: handlDate(data.openForm.checkTime),
            checkProductDetails: arr,
          }
          let commit
          let msgs = ''
          const a = 1
          if (a === 1) {
            commit = api.inventory.INVENTORY_CREATE
            msgs = '创建出'
          }
          commit(obj).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: msgs,
              })
              context.emit('succsess')
              close()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        }
      })
    }

    onMounted(() => {})
    return {
      ...toRefs(data),
      close,
      open,
      handlAdd,
      handlDelete,
      handlSubmit,
      querySearchAsync,
      handleSelect,
      handlDate,
      handlRddtype,
    }
  },
}
</script>

<style scoped>
/* @import url(); 引入css类 */
:deep(.tableForm .el-form-item--small.el-form-item) {
  margin-bottom: 0 !important;
}
</style>
